package com.stevin.tool;

import com.google.common.collect.Lists;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.junit.Test;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author mars
 * @date 2019/01/22
 */
@Slf4j
public class AutoRegisterTools {

    @Test
    public void searchOne() throws IOException {
        Lists.newArrayList("IPZ-961","ipz-928","ipz-889","ipz-998","ipz-908","supd-140","ipz-944","ipz-872").forEach(key -> {
            for (String magnet : MagnetSearchTool.searchMagnet2(key)) {
                if (createNewJob(magnet)) {
                    break;
                }
            }
        });
    }

    @Test
    public void printAllVIPMagnet() throws IOException {
        MagnetParseTool.VIP.parse("qishilicai").forEach(key -> {
            MagnetSearchTool.searchMagnet(key).forEach(log::info);
        });
    }

    @Test
    public void searchAllSeesaaWiki() throws InterruptedException, IOException {
        // %b0%ec%a5%ce%c0%a5%a4%e2%a4%e2
        MagnetParseTool.SeesaaWiki.parse("%c1%ea%c2%f4%a4%df%a4%ca%a4%df").parallelStream().forEach(key -> {
            for (String magnet : MagnetSearchTool.searchMagnet2(key)) {
                log.info("magnetUrl:{}", magnet);
                if (createNewJob(magnet)) {
                    break;
                }
            }
        });
    }


    @Test
    public void searchAllVIP() throws IOException {
        MagnetParseTool.VIP.parse("youbanshenxue").forEach(key -> {
            for (String magnet : MagnetSearchTool.searchMagnet(key)) {
                if (createNewJob(magnet)) {
                    break;
                }
            }
        });
    }


    @Test
    public void searchAllMgshd() throws IOException {
        MagnetParseTool.Mgshd.parse(1, "luxu").forEach(key -> {
            for (String magnet : MagnetSearchTool.searchMagnet(key)) {
                log.info("magnetUrl:{}", magnet);
                if (createNewJob(magnet)) {
                    break;
                }
            }
        });
    }

    @Test
    public void createNewJob() throws InterruptedException {
        createNewJob("magnet:?xt=urn:btih:9757c42a9d5758651cf36caafbde2e60d6c5b319&amp;dn=%5B44x.me%5DABP-733-C");
        TimeUnit.SECONDS.sleep(100);
    }


    private static boolean createNewJob(String magnet) {
        log.info("createNewJob magnetUrl:{}", magnet);
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://115.com/web/lixian/?ct=lixian&ac=add_task_url")
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "sign=bb06cdf4dbb0fa1f114ba5e926b944a9a04e8ae9&time=1548769580&uid=61204375&url=" + magnet))
                .addHeader("accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("origin", "https://115.com")
                .addHeader("x-requested-with", "XMLHttpRequest")
                .addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36 115Browser/8.6.5")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .addHeader("referer", "https://115.com/?cid=0&offset=0&tab=&mode=wangpan")
                .addHeader("accept-encoding", "gzip, deflate, br")
                .addHeader("accept-language", "en-US,en;q=0.8")
                .addHeader("cookie", "acw_tc=784e2c9c15487672032201748e4d14a66941cab2d82110f1760d8246cd62b1; UID=61204375_A1_1548769572; CID=cc8118edc1844b8b7b6bbd62ba5d1de0; SEID=8f45c32359900254d7d4bfa2d15c8cf9e155c5956485ac0f9e4c1cbf0fc2f8fd0141e669d4a14809c501b044ba179c68c1eeb785e7529c57f69f610f")
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "aa7db068-1604-6976-63cc-7c849cb2f607")
                .build();
        String responseBody = null;
        try {
            Response response = client.newCall(request).execute();
            responseBody = response.body().string();
            log.info("status:{} response:{}", response.message(), responseBody);
        } catch (Throwable e) {
            log.error(e.getMessage());
        }
        return isSuccess(responseBody);
    }


    private static boolean isSuccess(String jobResponse) {
        if (Objects.isNull(jobResponse)){
            return false;
        }
        JSONObject taskInfo = JSON.parseObject(jobResponse);
        if (Objects.isNull(taskInfo)){
            return false;
        }
        if (taskInfo.getIntValue("errcode") == 10008){
            return true;
        }
        if (taskInfo.getIntValue("errcode") == 911) {
            try {
                TimeUnit.SECONDS.sleep(60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (taskInfo.getIntValue("errcode") == 0 && taskInfo.getBoolean("state")) {
            log.info("break, find next magnetKey");
            return true;
        }
        return false;
    }

}
